package com.googlecode.allinclusive.fw.web.struts2.interceptor;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * URL请求拦截处理的基类
 * 
 * @author <a href="mailto:summerxyg@gmail.com">xiayg</a>
 */
@SuppressWarnings("serial")
public abstract class UrlActionInterceptor extends AbstractInterceptor {
	
	/** log实例*/
	private static final Log log = LogFactory.getLog(LoggingInterceptor.class);
	
	/** 忽略的URL*/
    protected String[] ignoreUrls = {};
    
	/**
	 * 请求拦截处理
	 */
    @Override
	public String intercept(ActionInvocation invocation) throws Exception {
		// 请求的URL路径
        ActionContext ac = invocation.getInvocationContext();
        HttpServletRequest request = (HttpServletRequest) ac.get(ServletActionContext.HTTP_REQUEST);
        final String requestURI = request.getRequestURI();

        if (ignore(requestURI)) {
        	if (log.isDebugEnabled()) {
        		log.debug("Skipping Interceptor[" + this.getClass().getSimpleName() + "] for request[" + requestURI  + "].");
        	}
        	return invocation.invoke();
        }
    	return doIntercept(invocation);
	}
	
    /**
     * 是否忽略该URL
     * @param requestURI 请求的URL路径
     * @return true/false
     */
    public boolean ignore(String requestURI) {
    	if (ignoreUrls == null) {
    		return false;
    	}
    	
    	boolean ignore = false;
        // 忽略的URL
        for (String ignoreUrl : ignoreUrls) {
        	if (requestURI.matches(ignoreUrl)) {
        		ignore = true;
        		break;
        	}
        }
        
    	return ignore;
    }
	
	/**
	 * 忽略的URL路径格式
	 * @param ignoreUrls 忽略的URL路径格式
	 */
	public void setIgnoreUrls(String ignoreUrls) {
		if (ignoreUrls == null || ignoreUrls.trim().length() == 0) {
			this.ignoreUrls = null;
		}
		this.ignoreUrls = ignoreUrls.split("\\s*[,]\\s*");
	}
	
    /**
     * Subclasses must override to implement the interceptor logic.
     * 
     * @param invocation the action invocation
     * @return the result of invocation
     * @throws Exception
     */
    protected abstract String doIntercept(ActionInvocation invocation) throws Exception;
}
